package com.example.pufang.controller.front;

import com.alibaba.fastjson.JSONArray;
import com.example.common.CommonResult;
import com.example.pufang.model.FileModel;
import com.example.utils.PufangUtils;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.*;

@RestController
@RequestMapping("/front")
@CrossOrigin
@Api(tags = "h5用户文件上传接口")
public class FileFrontController {

    private static final Logger logger = LoggerFactory.getLogger(FileFrontController.class);

    /**
     * 本地保存路径
     */
    @Value("${file.path}")
    private String dirPath;

    @RequestMapping(value = "/upload")
    public CommonResult<Map<String, List<FileModel>>> upload(@RequestParam(value = "file") MultipartFile[] multipartFiles)
            throws IOException {

        HashMap<String, List<FileModel>> map = new HashMap<>();

        // 获取当前系统时间，按照日期存储文件
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());

        String folderPath = calendar.get(Calendar.YEAR) + "/"
                + ( calendar.get(Calendar.MONTH) + 1) + "/"
                + calendar.get(Calendar.DAY_OF_MONTH) + "/";
        String fullPath = dirPath + folderPath;
        // 判断是否有文件夹，没有创建
        File folder = new File(fullPath);
        if (!folder.exists() && !folder.isDirectory()) {
            folder.mkdirs();
        }

        List<FileModel> urlList = new ArrayList<>();

        for (MultipartFile file : multipartFiles) {
            InputStream inputStream = file.getInputStream();
            //文件后缀
            String prefix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String fileName = new PufangUtils().getUuid() + prefix;
            Files.copy(inputStream,new File(fullPath + fileName).toPath(), StandardCopyOption.REPLACE_EXISTING);
            //拼接上传文件完整路径
            // String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
            //         .path(folderPath + fileName)
            //         .toUriString();

            // 拼接上传文件存储路径
            String fileDownloadUri = folderPath + fileName;

            urlList.add(new FileModel(fileDownloadUri));
        }

        map.put("urls", urlList);

        return CommonResult.success(map);
    }

}
